import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib.font_manager
from pyod.models.abod import ABOD

from pyod.utils.data import generate_data,get_outliers_inliers

X_train, Y_train = generate_data(n_train=200,train_only=True, n_features=2)
# 拆分出异常数据和正常数据
x_outliers, x_inliers = get_outliers_inliers(X_train,Y_train)

#模型训练
from pyod.models.knn import KNN
outlier_fraction = 0.1#异常值比例
knn = KNN(contamination=outlier_fraction)#生成模型
knn.fit(X_train)#训练模型
score = knn.decision_scores_# 注意异常得分是负的
score = score * -1
print (score.shape)


#预测结果
y_pred = knn.predict(X_train)# 预测训练样本的标签
from sklearn.metrics import classification_report
print(classification_report(y_true=Y_train,y_pred=y_pred))

n_inliers = len(x_inliers)
n_outliers = len(x_outliers)
#生成热力图的坐标点
xx , yy = np.meshgrid(np.linspace(-10, 10, 200), np.linspace(-10, 10, 200))
# 根据百分比生成
threshold = -knn.threshold_

# 得到每个坐标点的异常值得分
Z = knn.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1
Z = Z.reshape(xx.shape)
plt.figure(figsize=(10, 10))
#将正常样本区域绘制成蓝色
plt.contourf(xx, yy, Z, levels = np.linspace(Z.min(), threshold, 10),cmap=plt.cm.Blues_r)
#绘制决策曲线
a = plt.contour(xx, yy, Z, levels=[threshold],linewidths=2, colors='red')
#将异常样本区域绘制成橘黄色
plt.contourf(xx, yy, Z, levels=[threshold, Z.max()],colors='orange')
#绘制正常点（白色）
b = plt.scatter(X_train[:-n_outliers, 0], X_train[:-n_outliers, 1], c='white',s=20, edgecolor='k')
# 绘制异常点（黑色）
c = plt.scatter(X_train[-n_outliers:, 0], X_train[-n_outliers:, 1], c='black',s=20, edgecolor='k')
plt.axis('tight')

plt.legend(
    [a.collections[0], b, c],
    ['learned decision function', 'true inliers', 'true outliers'],
    prop=matplotlib.font_manager.FontProperties(size=10),
    loc='lower right')

plt.title('10.KNN')
plt.xlim((-10, 10))
plt.ylim((-10, 10))
plt.show()
